<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\PaymentAgentPaidCompany as PaymentAgentPaidCompanyModel;
use app\payment\model\PaymentPaidCompany as PaymentPaidCompanyModel;
use app\payment\model\Mconfig as MconfigModel;

/**
 * 代理代付通道配置控制器
 */
class AgentPaidCompany extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if (!in_array(request()->action(), ['index', 'see'])) {
            if ($this->no_auth) {
                $this->error('权限不足！');
            }
        }

        if (in_array(request()->action(), ['add'])) {
            if (!$this->add_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['edit'])) {
            if (!$this->edit_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['delete'])) {
            if (!$this->delete_safe) {
                $this->error('NO');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 设置搜索参数
        $search = ['company_name' => '通道编号', 'merchant_id' => '代理商户号'];

        // 获取查询条件
        $map = $this->getMap();

        if ($this->no_auth) {
            $map[] = ['merchant_id', '=', $this->merchant_id];
            unset($search['merchant_id']);
        }

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = PaymentAgentPaidCompanyModel::where($map)->order('create_time desc')->paginate($list_rows);
        // 分页数据
        $page = $data_list->render();

        $items = [
            ['id', 'ID'],
            ['merchant_id', '代理商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['company_name', '通道编号', 'callback', function ($value) {
                $title = PaymentPaidCompanyModel::where(['name' => $value])->value('title');
                return $value . '<br/>' . $title;
            }, '', 'text-center'],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'status'],
            ['right_button', '操作', 'btn']
        ];
        $hideCheckbox = false;
        if ($this->no_auth) {
            $hideCheckbox = true;
        }
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox($hideCheckbox)
            ->setPageTitle('代理代付通道配置') // 设置页面标题
            ->setTableName('payment_agent_paid_company') // 设置数据表名
            ->setPrimaryKey('id') // 设置主键名为id
            ->setSearch($search) // 设置搜索参数
            ->addColumns($items)
            ->addTopButtons('add,enable,disable,delete') // 批量添加顶部按钮
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 验证
            $result = $this->validate($data, 'AgentPaidCompany');
            if (true !== $result) {
                $this->error($result);
            }

            $temp_map[] = ['merchant_id', '=', $data['merchant_id']];
            $temp_map[] = ['company_name', '=', $data['company_name']];
            $info = PaymentAgentPaidCompanyModel::where($temp_map)->find();
            if ($info) {
                $this->error("请刷新，数据已经存在！");
            }

            if ($temp = PaymentAgentPaidCompanyModel::create($data)) {
                // 记录行为
                action_log('payment_agent_paid_company_add', 'payment_agent_paid_company', $temp['id'], UID, json_encode($temp));
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }
        // 代付公司    
        $paid_company = PaymentPaidCompanyModel::where(['status' => 1])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('title', 'name');

        $all_merchants = [];
        $all_merchant = MconfigModel::where(['status' => 1, 'agent_status' => 1])->column('id');
        if ($all_merchant) {
            foreach ($all_merchant as $key => $value) {
                $all_merchants[$value] = get_user_nickname($value);
            }
        }
        $id = date('YmdHis');

        $items = [
            ['hidden', 'id', $id],
            ['select', 'merchant_id', '代理商户号', '', $all_merchants],
            ['select', 'company_name', '通道名称', '', $paid_company],
            ['text', 'paid_start_price', '每次代付开始扣除金额', '', '0'],
            ['text', 'paid_rate', '代付费率', '', '0'],
            ['radio', 'status', '状态', '', ['禁用', '启用'], 1],
            ['password', 'trade_pwd', '交易密码', '6-16位']
        ];

        $tips = "请勿填错！设置代理代付通道的每次代付开始扣除金额和代付费率要大于代付公司的每次代付开始扣除金额和代付费率，才有返利！";
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems($items)
            ->setPageTips($tips)
            ->fetch();
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }
        // 获取数据
        $info = PaymentAgentPaidCompanyModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        // 代付公司    
        $paid_company = PaymentPaidCompanyModel::where([])->order('sort asc,name asc')->column('title', 'name');

        $items = [
            ['hidden', 'id', $id],
            ['static', 'merchant_id', '代理商户号', '代理商户名称：' . get_user_nickname($info['merchant_id'])],
            ['static', 'company_name', '通道名称', '通道名称：' . $paid_company[$info['company_name']]],
            ['static', 'paid_start_price', '每次代付开始扣除金额'],
            ['static', 'paid_rate', '代付费率'],
            ['radio', 'status', '状态', '', ['禁用', '启用']],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
        ];

        $tips = "请勿填错！设置代理代付通道的每次代付开始扣除金额和代付费率要大于代付公司的每次代付开始扣除金额和代付费率，才有返利！";
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->setPageTips($tips)
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 验证
            $result = $this->validate($data, 'AgentPaidCompany');
            if (true !== $result) {
                $this->error($result);
            }

            if ($temp = PaymentAgentPaidCompanyModel::update($data)) {
                // 记录行为
                action_log('payment_agent_paid_company_edit', 'payment_agent_paid_company', $temp['id'], UID, json_encode($temp));
                $this->success('编辑成功', url('index'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = PaymentAgentPaidCompanyModel::where('id', $id)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->no_auth) {
            if ($this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        // 代付公司    
        $paid_company = PaymentPaidCompanyModel::where([])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('title', 'name');

        $all_merchants = [];
        $all_merchant = MconfigModel::where(['status' => 1, 'agent_status' => 1])->column('id');
        if ($all_merchant) {
            foreach ($all_merchant as $key => $value) {
                $all_merchants[$value] = get_user_nickname($value);
            }
        }

        $items = [
            ['hidden', 'id', $id],
            ['select', 'merchant_id', '代理商户号', '', $all_merchants],
            ['select', 'company_name', '通道名称', '', $paid_company],
            ['text', 'paid_start_price', '每次代付开始扣除金额', '', '0'],
            ['text', 'paid_rate', '代付费率', '', '0'],
            ['radio', 'status', '状态', '', ['禁用', '启用'], 1],
        ];

        $tips = "请勿填错！设置代理代付通道的每次代付开始扣除金额和代付费率要大于代付公司的每次代付开始扣除金额和代付费率，才有返利！";
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems($items)
            ->setFormData($info) // 设置表单数据
            ->setPageTips($tips)
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 
     * @return mixed
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record 
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids_delete = is_array($ids) ? '' : $ids;
        $data = PaymentAgentPaidCompanyModel::where('id', 'in', $ids)->column('id');
        return parent::setStatus($type, ['payment_agent_paid_company_' . $type, 'payment_agent_paid_company', $ids_delete, UID, implode('、', $data)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id = input('post.pk', '');
        $field = input('post.name', '');
        $value = input('post.value', '');
        $data = PaymentAgentPaidCompanyModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $data . ')，新值：(' . $value . ')';
        return parent::quickEdit(['payment_agent_paid_company_edit', 'payment_agent_paid_company', $id, UID, $details]);
    }
}
